//
//  MLUserDataViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/26.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#define chooseBtnTag 100

#import "MLUserDataViewController.h"
#import "UserDataEditCell.h"
#import "VoiceCell.h"

#import "ChatListViewController.h"
#import "ChatViewController.h"
#import "ChatViewController.h"
#import "MLTabBar.h"
#import "UserDataEditPhoto.h"
#import "UserDataEditViewController.h"
#import "MLHomeViewController.h"

#import "MLAudioPlayer.h"
#import "AmrPlayerReader.h"

#import "HJActionSheet.h"
#import "RDImageViewerController.h"
#import "UserDataEditTagCell.h"
#import "JCTagListView.h"
#import "ReportUploadImageViewController.h"

@interface MLUserDataViewController ()<UITableViewDelegate,UITableViewDataSource,HJActionSheetDelegate,UserDataEditPhotoDelegate>
//视图列表
{
    UIButton *chatBtn;
   // BOOL f5Bool;

}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *userInfoArr;
@property (nonatomic, strong)NSMutableArray *userDetailsArr;
@property (nonatomic, strong)NSMutableArray *userSkillsArr;
@property (nonatomic, strong)NSMutableArray *userSkillsTitleArr;


@property (nonatomic, strong)UIButton *likeBtn;
@property (nonatomic, strong)UIButton *reportBtn;
@property (nonatomic, strong)UIView *bottomView;//底层view

//图片库
@property (nonatomic, strong)UserDataEditPhoto *userPhoto;
//@property (strong, nonatomic)NSString *interestTopic;//兴趣话题
//@property (strong, nonatomic)NSString *sweetheartTime;//恋爱时长

// 声线列表
@property (strong, nonatomic) NSMutableArray *voiceArray;

@property (strong, nonatomic) NSMutableArray *voiceFileArray;

// 音频播放
@property (nonatomic, strong) MLAudioPlayer *player;
@property (nonatomic, strong) AmrPlayerReader *amrReader;

@property NSInteger voicePlayIndex;

@property NSInteger voicePlayStatus;

// 共享的音频播放计时器
@property (nonatomic, strong) NSTimer *updateAudioUITimer;

// 判断是否是用户自己
@property BOOL isCurrentUser;

//防止多次喜欢
@property BOOL is;

//通话申请防止多次
@property BOOL chatIs;
//约会状态
//@property (nonatomic, strong)MLDate *date;

//@property (nonatomic, strong) JCTagListView *tagListView1;
//@property (nonatomic, strong) JCTagListView *tagListView2;

//@property CGFloat h1;
@property CGFloat h2;
//@property CGFloat h3;
@property CGFloat h4;
//
@property (nonatomic, strong) UIView *headview;

@property BOOL upData;
@end

@implementation MLUserDataViewController
{
    //用户年龄
    UILabel *userAge;
    //用户信息
    UILabel *userInfo;
   // UIImageView *biaoshiimage;//专属恋人
    UIView *realauthentic;//真人认证
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([self.userData.objectId isEqualToString:[MLUser currentUser].objectId]) {
        
        if (self.upData) {
             [self upUserData:YES];
        }else{
            self.upData = YES;
        }
    }
  //  f5Bool = NO;

//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.tableView reloadData];
//    });
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    for (int i = 0; i<2; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        UserDataEditTagCell *tagCell =(UserDataEditTagCell *) [self.tableView cellForRowAtIndexPath:indexPath];
        if (tagCell) {
//            if ([tagCell.titleLabel.text isEqualToString:@"我想"]) {
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h1 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//                
//            }else
                if ([tagCell.titleLabel.text isEqualToString:@"理想对象"]){
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h2 = tagCell.tagListView.collectionView.contentSize.height;
                }
            
            }else
//                if ([tagCell.titleLabel.text isEqualToString:@"特技"]) {
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h3 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//                
//            }else
                if ([tagCell.titleLabel.text isEqualToString:@"兴趣"]){
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h4 = tagCell.tagListView.collectionView.contentSize.height;
                }
            }
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}
//即将退出视图
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    // 关闭语音播放
    [self.player stopPlaying];
    [self.updateAudioUITimer invalidate];
    self.updateAudioUITimer = nil;
}


-(void)rightItemAction
{
    UserDataEditViewController *editController = [[UserDataEditViewController alloc]init];
    editController.voiceArray = self.voiceArray;
    editController.voiceFileArray = self.voiceFileArray;
    [editController quit:^{
       //保存退出
        [self.tableView reloadData];
        
    }];
    
    [Utils pushTabbarHidden:editController Selfvc:self];
}

#pragma mark - life cycle

-(void)upUserData:(BOOL)PhotoUp
{
   
    [self.headview addSubview:userAge];
    [self.headview addSubview:userInfo];
   // [self.headview addSubview:biaoshiimage];
    [self.headview addSubview:realauthentic];
    if (PhotoUp) {
        // 获取相册内容
        AVQuery *galleryQuery = [MLGallery query];
        [galleryQuery whereKey:@"belong_to" equalTo:self.userData];
        [galleryQuery includeKey:@"images"];
        __weak MLUserDataViewController *weakSelf = self;
        [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            weakSelf.myGallery = (MLGallery *)object;
            CGFloat height = weakSelf.myGallery.images.count>4 ? DeviceWidth, (DeviceWidth/2.5)+30 : (DeviceWidth, (DeviceWidth/2.5)+30)/2;
            weakSelf.userPhoto.frame = CGRectMake(-1, 0, DeviceWidth, height+55);
            weakSelf.tableView.tableHeaderView = weakSelf.userPhoto;
            weakSelf.headview.frame = CGRectMake(0, height, DeviceWidth, 45);
            //图片集
            weakSelf.userPhoto.Gallery = weakSelf.myGallery;
            [weakSelf.userPhoto setUpPhotoView];
            [weakSelf.tableView reloadData];
        }];
    }else{
        CGFloat height = self.myGallery.images.count>4 ? DeviceWidth, (DeviceWidth/2.5)+30 : (DeviceWidth, (DeviceWidth/2.5)+30)/2;
        self.userPhoto.frame = CGRectMake(-1, 0, DeviceWidth, height+55);
        self.tableView.tableHeaderView = self.userPhoto;
        self.headview.frame = CGRectMake(0, height, DeviceWidth, 45);
       [self.userPhoto setUpPhotoView];
    }
    self.title = self.userData.nickname;

    //self.userInfoArr = [NSMutableArray array];
    
//    if (self.userData.type != MLUserType_NORMAL) {
//        //不是普通人
//        //标题
//        self.userInfoArr = [NSMutableArray arrayWithArray:@[[@[@"团员号", @"内心独白", @"声线", @"我属于", @"叫我"]mutableCopy], [@[@"兴趣话题",@"我想",@"理想的你",@"特技",@"喜欢"]mutableCopy],[@[@"外貌",@"职业",@"语言",@"恋爱时长"]mutableCopy]]];
//    }else{
//        //普通人
//        //标题
//        self.userInfoArr = [NSMutableArray arrayWithArray:@[[@[@"团员号", @"内心独白", @"声线", @"我属于", @"叫我"]mutableCopy], [@[@"兴趣话题",@"我想",@"理想的你",@"特技",@"喜欢"]mutableCopy],[@[@"外貌",@"职业",@"语言"]mutableCopy]]];
//    }
     self.userInfoArr = [NSMutableArray arrayWithArray:@[[@[@"团员号", @"内心独白", @"声线", @"毕业院校", @"职业"]mutableCopy], [@[@"理想对象",@"兴趣"]mutableCopy],[@[@"身高",@"故乡",@"语言",@"顾问印象"]mutableCopy]]];
    
    
//    NSString *salutationMeStr = [[NSString alloc]init];
//    for (int i = 0 ; i < [self.userData.called_tags count]; i++) {
//        if (i == [self.userData.called_tags count]-1) {
//            salutationMeStr = [salutationMeStr stringByAppendingString:[NSString stringWithFormat:@"%@",[self.userData.called_tags objectAtIndex:i]]];
//        }else{
//            salutationMeStr = [salutationMeStr stringByAppendingString:[NSString stringWithFormat:@"%@、",[self.userData.called_tags objectAtIndex:i]]];
//        }
//    }
    
    
    
    NSString *languagestr = [[NSString alloc]init];
    for (int i = 0 ; i < [self.userData.language count]; i++) {
        if (i == [self.userData.language count]-1) {
            languagestr = [languagestr stringByAppendingString:[NSString stringWithFormat:@"%@",[self.userData.language objectAtIndex:i]]];
        }else{
            languagestr = [languagestr stringByAppendingString:[NSString stringWithFormat:@"%@、",[self.userData.language objectAtIndex:i]]];
        }
    }
    
//    NSString *specialstr = [[NSString alloc]init];
//    for (int i = 0 ; i < [self.userData.special count]; i++) {
//        if (i == [self.userData.special count]-1) {
//            specialstr = [specialstr stringByAppendingString:[NSString stringWithFormat:@"%@",[self.userData.special objectAtIndex:i]]];
//        }else{
//            specialstr = [specialstr stringByAppendingString:[NSString stringWithFormat:@"%@、",[self.userData.special objectAtIndex:i]]];
//        }
//    }
    
    NSArray *arrAr = [NSArray array];
    //兴趣
    NSArray *like_tags = self.userData.like_tags.count !=0 ? self.userData.like_tags:arrAr;
  //  NSArray *special_tags = self.userData.special.count !=0 ? self.userData.special:arrAr;
    //NSArray *wan_tags = self.userData.want_tags.count !=0 ? self.userData.want_tags:arrAr;
    
    //理想对象
    NSArray *ideal_tags = self.userData.ideal_tags.count !=0 ? self.userData.ideal_tags:arrAr;
    
//    if (self.userData.type != MLUserType_NORMAL) {
//        //不是普通人
////        self.interestTopic = self.userData.interestTopic;
////        //恋爱时长
////        if(self.userData.sweetheartTime){
////            self.sweetheartTime = [NSString stringWithFormat:@"%ld分钟",(long)self.userData.sweetheartTime];
////        }else{
////            self.sweetheartTime = @"初恋还在哦";
////        }
//        self.userDetailsArr = [NSMutableArray arrayWithArray:@[[@[[NSString stringWithFormat:@"%ld",(long)self.userData.molianId], [NSString stringWithFormat:@"%@",self.userData.intro] ,self.userData.isHasVoice ? @"声线":@"", [NSString stringWithFormat:@"%@",self.userData.belong], salutationMeStr]mutableCopy],[@[self.interestTopic?self.interestTopic:@"",wan_tags,ideal_tags, special_tags,like_tags]mutableCopy],[@[[NSString stringWithFormat:@"%@",self.userData.figure],[NSString stringWithFormat:@"%@",self.userData.job],[NSString stringWithFormat:@"%@",languagestr],self.sweetheartTime]mutableCopy]]];
//    }else{
//        //普通人
//      //  self.interestTopic = self.userData.interestTopic;
//        self.userDetailsArr = [NSMutableArray arrayWithArray:@[[@[[NSString stringWithFormat:@"%ld",(long)self.userData.molianId], [NSString stringWithFormat:@"%@",self.userData.intro] ,self.userData.isHasVoice ? @"声线":@"", [NSString stringWithFormat:@"%@",self.userData.belong], salutationMeStr]mutableCopy],[@[self.interestTopic?self.interestTopic:@"", wan_tags,ideal_tags,special_tags,like_tags]mutableCopy],[@[[NSString stringWithFormat:@"%@",self.userData.figure],[NSString stringWithFormat:@"%@",self.userData.job],[NSString stringWithFormat:@"%@",languagestr]]mutableCopy]]];
//        
//    }
    
    
    self.userDetailsArr = [NSMutableArray arrayWithArray:@[[@[[NSString stringWithFormat:@"%ld",(long)self.userData.molianId], [NSString stringWithFormat:@"%@",self.userData.intro] ,self.userData.isHasVoice ? @"声线":@"", [NSString stringWithFormat:@"%@",self.userData.school], [NSString stringWithFormat:@"%@",self.userData.job]]mutableCopy],[@[ideal_tags,like_tags]mutableCopy],[@[[NSString stringWithFormat:@"%ld",self.userData.height],[NSString stringWithFormat:@"%@",self.userData.location_city],[NSString stringWithFormat:@"%@",languagestr],self.userData.impress?self.userData.impress:@""]mutableCopy]]];
    
    //CELL数据
   // self.userDetailsArr = [NSMutableArray array];
    

    
    
    
    
    for (int i = 0 ; i <self.userDetailsArr.count ; i++) {
        for (int j = 0 ; j < [[self.userDetailsArr objectAtIndex:i] count]; j++) {
            id obj = self.userDetailsArr[i][j];
            if (obj == nil||[obj isEqual:@""]||obj == arrAr || [obj isEqual:nil] || [obj isEqual:[NSNull null]] || [obj isEqual:@"(null)"]) {
                [self.userDetailsArr[i] removeObjectAtIndex:j];
                [self.userInfoArr[i] removeObjectAtIndex:j];
                j--;
            }
        }
    }
    
    
    //用户年龄
    userAge.text = [NSString stringWithFormat:@"%ld", (long)[self.userData getUserAge]];
    //其他信息
    userInfo.text = [NSString stringWithFormat:@"%@ %@", [self.userData getUserConstellation],self.userData.selectCity ? self.userData.selectCity:@""];
    userAge.frame = CGRectMake(20, (45-15)/2, 26, 15);
    userInfo.frame = CGRectMake(50, (45-15)/2, [Utils LabeSizeText:userInfo.text Font:userInfo.font].width, 15);
//    UIImage *image;
//    if (self.userData.type == MLUserType_NORMAL) {
//        image = [UIImage imageNamed:@"实习恋人_2"];
//    }else if (self.userData.type == MLUserType_POCKET){
//        image = [UIImage imageNamed:@"专属恋人_2"];
//    }else if (self.userData.type == MLUserType_RECOMMENDED){
//        image = [UIImage imageNamed:@"梦想恋人_2"];
//    }
//    biaoshiimage.image = image;
//    biaoshiimage.frame = CGRectMake(CGRectGetMaxX(userInfo.frame)+5, (45-15)/2, 56, 15);
    if (self.userData.realAuthentic == 1 ) {
        realauthentic.hidden = NO;
    }else{
        realauthentic.hidden = YES;
    }
    [self.tableView setContentOffset:CGPointMake(0, 2000)animated:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView setContentOffset:CGPointMake(0, -64)animated:NO];
    });
    
    [self.tableView reloadData];
    
}
//举报
- (void)rightItemInform
{
    HJActionSheet *sheet = [[HJActionSheet alloc]initWithTitle:nil Delegate:self destructiveButtonTitle:@"取消" OtherButtonTitles:@[@"举报并上传截图"]];
    sheet.Delegate = self;
    [sheet show];
}
-(void)hjActionSheet:(UIButton *)sender clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSArray *arr = @[@"举报并上传截图"];
    if (buttonIndex < arr.count) {
        NSString *str = [arr objectAtIndex:buttonIndex];
        //先查询是否举报过了
        AVQuery *query = [MLReportRecord query];
        [query whereKey:@"reportee" equalTo:self.userData];
        [query whereKey:@"reporter" equalTo:[MLUser currentUser]];
        [query whereKey:@"status" equalTo:[NSNumber numberWithInteger:MLReportRecordStatus_NORMAL]];
        __weak MLUserDataViewController *weakSelf = self;
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error&&objects.count) {
                //以后考虑自定义UIAlertView
                [HUD Prompt:@"你已经举报过了"];
            }else{
                if([str isEqualToString:@"举报并上传截图"]){
                    ReportUploadImageViewController *reportUIVC =  [[ReportUploadImageViewController alloc] init];
                    reportUIVC.reportee = weakSelf.userData;
                    [Utils pushTabbarHidden:reportUIVC Selfvc:self];
                }else{
                    
                    MLReportRecord *report =[MLReportRecord object];
                    MLUser *u = [MLUser currentUser];
                    report.reportee = weakSelf.userData;
                    report.reporter = u;
                    report.remark = str;
                    report.status = MLReportRecordStatus_NORMAL;
                    [report saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [AVAnalytics event:@"举报"]; // 通知服务器一个点击事件。
                            [HUD Prompt:@"举报成功"];
                            NSDictionary *params = @{@"touserId": [MLUser currentUser].objectId,@"type":@3};
                            [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
                                
                            }];
                            NSDictionary *nparams = @{@"userId":weakSelf.userData.objectId};
                            [AVCloud callFunctionInBackground:@"reportUser" withParameters:nparams block:^(id object, NSError *error) {
                                
                            }];
                        }else{
                            [HUD Prompt:@"请返回后重试"];
                        }
                    }];
                    
                }
                
                
               
            }
        }];
        
    }
}

- (void)crash {
    [NSException raise:NSGenericException format:@"只是测试，模拟一条崩溃信息。"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //[self performSelector:@selector(crash) withObject:nil afterDelay:5.0];
    self.is = NO;
    self.chatIs = NO;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [AVAnalytics event:@"个人资料页面访问"]; // 通知服务器一个like点击事件。
   // f5Bool = NO;

    MLUser *currentUser = [MLUser currentUser];
    if (currentUser&&[currentUser.objectId isEqualToString:self.userData.objectId ]) {
        self.isCurrentUser = YES;
        if(!self.redact){
            UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction)];
            self.navigationItem.rightBarButtonItem = rightItem;
        }

    }

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = UIColorFromRGB(0xececec);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
    //    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0);//滚动条偏移量
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 90, 0, 0)];
    [self.view addSubview:self.tableView];
    
    //用户年龄
    userAge = [[UILabel alloc]init];
    if (self.userData.gender == MLUserGender_MALE) {
        [userAge setBackgroundColor:RGBA(162, 200, 243, 1)];
    } else {
        [userAge setBackgroundColor:RGBA(245, 163, 179, 1)];
    }
    [userAge.layer setCornerRadius:15/2];
    userAge.clipsToBounds = YES;
    userAge.font = [UIFont fontWithName:FontName size:16];
    [self labelStyle:userAge];
    userAge.textColor = [UIColor whiteColor];
    
    //用户信息
    userInfo = [[UILabel alloc]init];
    [self labelStyle:userInfo];
    userInfo.textAlignment = NSTextAlignmentLeft;
    userInfo.textColor = [UIColor grayColor];
    userInfo.font = [UIFont fontWithName:FontName size:14];
    
    
//    biaoshiimage = [[UIImageView alloc]init];
//    [biaoshiimage setContentMode:UIViewContentModeScaleAspectFit];
//    biaoshiimage.clipsToBounds = YES;
//
    realauthentic = [[UIView alloc] initWithFrame:CGRectMake(DeviceWidth-95, (45-16)/2, 80, 16)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
    imageView.image = [UIImage imageNamed:@"真人认证"];
    
    [realauthentic addSubview:imageView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imageView.frame.origin.x + 16+ 5, imageView.frame.origin.y, 56, 16)];
    label.textColor = RGBA(135, 135, 135, 1);
    label.font = kFont(14);
    label.text = @"真人认证";
    [realauthentic addSubview:label];
//
    realauthentic.backgroundColor = [UIColor clearColor];
    realauthentic.hidden = YES;
//    // 获取相册内容
    AVQuery *galleryQuery = [MLGallery query];
    __weak MLUserDataViewController *weakSelf = self;
    [galleryQuery whereKey:@"belong_to" equalTo:weakSelf.userData];
    [galleryQuery includeKey:@"images"];
    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        weakSelf.myGallery = (MLGallery *)object;
        if (!weakSelf.myGallery) {
            // 找不到,创建新相册
            weakSelf.myGallery = [MLGallery object];
            weakSelf.myGallery.name = @"default gallery";
            weakSelf.myGallery.images = @[];
            weakSelf.myGallery.belong_to = [MLUser currentUser];
            weakSelf.myGallery.intro = @"";
        } else {
            if (weakSelf.myGallery.images.count != 0) {
                CGFloat height = weakSelf.myGallery.images.count>4 ? DeviceWidth, (DeviceWidth/2.5)+30 : (DeviceWidth, (DeviceWidth/2.5)+30)/2;
                weakSelf.userPhoto = [[UserDataEditPhoto alloc]initWithFrame:CGRectMake(-1, 0, DeviceWidth, height+55)];
                weakSelf.userPhoto.Gallery = weakSelf.myGallery;
            
                weakSelf.userPhoto.delegate = weakSelf;
//                [weakSelf.userPhoto setUpPhotoView];
                [weakSelf.tableView addSubview:weakSelf.userPhoto];
                weakSelf.userPhoto.backgroundColor = [UIColor groupTableViewBackgroundColor];
                self.tableView.tableHeaderView = weakSelf.userPhoto;
                
                self.headview = [[UIView alloc]initWithFrame:CGRectMake(0, height, DeviceWidth, 45)];
                self.headview.backgroundColor = [UIColor whiteColor];
                [weakSelf.userPhoto addSubview:self.headview];
                
                [self.headview addSubview:userAge];
                [self.headview addSubview:userInfo];
//                [self.headview addSubview:biaoshiimage];
              [self.headview addSubview:realauthentic];
            }
        }
        [self upUserData:NO];


    }];
    
  [self upUserData:NO];

    
    if (self.isCurrentUser) {
        // 是自己的页面, 添加编辑按钮等
    } else if(self.userData) {
        [self setOthersContent];
    }else{
        
    }
    // 初始化音频
    [self initAudioReader];
    // 获取已有的声线列表
    [self initVoiceContent];
    
    
    [chatBtn setTitle:@" 申请试恋" forState:UIControlStateNormal];
    //_bottomView.hidden = NO;
//    if ([Utils isFriendObjectId:self.userData.objectId]) {
//        //是好友不需要查询关系
//        [chatBtn setTitle:@"打电话" forState:UIControlStateNormal];
//        _bottomView.hidden = NO;
//    }else{
//        //检查通话权限
//        [self inquireChatStatus];
//    }
    [self.tableView setContentOffset:CGPointMake(0 , 0)animated:YES];
    
    
    if (self.initiation) {
        UserDataEditViewController *editController = [[UserDataEditViewController alloc]init];
        editController.voiceArray = self.voiceArray;
        editController.voiceFileArray = self.voiceFileArray;
        [editController quit:^{
            //保存退出
            [self.tableView reloadData];
        }];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:editController animated:NO];
        
    }
    

}

#pragma mark --UserDataEditPhotoDelegate
- (void)selfNavigationControllerPushVC:(RDImageViewerController *)viewController
{
    [self.navigationController pushViewController:viewController animated:YES];
}
#pragma mark - init user content

- (void)initAudioReader {
    // 初始化音频播放器
    MLAudioPlayer *player = [[MLAudioPlayer alloc]init];
    AmrPlayerReader *amrReader = [[AmrPlayerReader alloc]init];
    player.fileReaderDelegate = amrReader;
    
    self.player = player;
    self.amrReader = amrReader;
}

- (void)initVoiceContent {
    // 获取声线内容
    AVQuery *voiceQuery = [MLVoice query];
    [voiceQuery whereKey:@"belong_to" equalTo:self.userData];
    __weak MLUserDataViewController *weakSelf = self;
    [voiceQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            weakSelf.voiceArray = [NSMutableArray arrayWithArray:objects];
            [weakSelf.tableView reloadData];
        }
        
        // 获取声线文件并保持
        if (!weakSelf.voiceFileArray) {
            weakSelf.voiceFileArray = [[NSMutableArray alloc]init];
        }
        for (MLVoice *voice in weakSelf.voiceArray) {
            AVFile *voiceFile = [AVFile fileWithURL:voice.voice.url];
            [voiceFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                if (!error) {
                    NSString *path = NSTemporaryDirectory();
                    NSString *voiceFilePath = [path stringByAppendingPathComponent:voice.objectId];
                    // 将数据保存到指定的文件中
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    // 如果这个文件不存在则创建
                    if (![fileManager fileExistsAtPath:voiceFilePath]) {
                        [fileManager createFileAtPath:voiceFilePath contents:data attributes:nil];
                    }
                    [weakSelf.voiceFileArray addObject:voiceFilePath];
                }
            }];
        }
    }];
}

// 设置其他用户的内容, 如底部按钮
- (void)setOthersContent {
    /****** 底部按钮 ******/
    self.bottomView = [[UIView alloc]init];
    self.bottomView.frame = CGRectMake(0, DeviceHeight-40, DeviceWidth, 40);
    self.bottomView.backgroundColor =[UIColor whiteColor];
    CGFloat likeBtnWidth = DeviceWidth / 3;
    
    // 举报按钮
    self.reportBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, likeBtnWidth, 40)];
    [self.reportBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [self.reportBtn setImage:[UIImage imageNamed:@"data_jubao_icon"] forState:UIControlStateNormal];
    [self.reportBtn setImage:[UIImage imageNamed:@"data_jubao_icon"] forState:UIControlStateSelected];
    [self.reportBtn setTitle:@" 举报" forState:UIControlStateNormal];
    self.reportBtn.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [self.bottomView addSubview:self.reportBtn];
    [self.reportBtn addTarget:self action:@selector(rightItemInform) forControlEvents:UIControlEventTouchUpInside];

    
    // 喜欢按钮
    self.likeBtn = [[UIButton alloc]initWithFrame:CGRectMake(likeBtnWidth, 0, likeBtnWidth, 40)];
    [self.likeBtn setImage:[UIImage imageNamed:@"data_like__normal_icon"] forState:UIControlStateNormal];
    [self.likeBtn setImage:[UIImage imageNamed:@"data_like_press_icon"] forState:UIControlStateSelected];
    self.likeBtn.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [self.likeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    
    NSString *count = [[ShareData shareData].likeUserDic objectForKey:self.userData.objectId];
    if (!count) {
        count = [NSString stringWithFormat:@"%ld",(long)self.userData.likeCount];
        [[ShareData shareData].likeUserDic setObject:count forKey:self.userData.objectId];
    }
    
    [self.likeBtn setTitle:[NSString stringWithFormat:@" %@",count] forState:UIControlStateNormal];
    [self.likeBtn addTarget:self action:@selector(likeUserAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 设置用户被喜欢的状态
    BOOL isLiked = NO;
    if([Utils isLoveUserObjectId:self.userData.objectId]){
        isLiked = YES;
    }
    
    if (isLiked) {
        self.likeBtn.selected = YES;
        [[self.likeBtn layer] setBorderColor:APPCOLOR(1).CGColor];
    } else {
        self.likeBtn.selected = NO;
        [[self.likeBtn layer] setBorderColor:[UIColor grayColor].CGColor];
    }
    
    [ self.bottomView addSubview:self.likeBtn];

    // 去聊天按钮
    chatBtn = [[UIButton alloc]initWithFrame:CGRectMake(likeBtnWidth*2, 0,likeBtnWidth , 40)];
    [chatBtn setImage:[UIImage imageNamed:@"data_chat_icon"] forState:UIControlStateNormal];
    [chatBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    chatBtn.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [chatBtn addTarget:self action:@selector(goToChatAction) forControlEvents:UIControlEventTouchUpInside];
    [ self.bottomView addSubview:chatBtn];
    
    UIView *separatorView = [[UIView alloc]init];
    [separatorView setFrame:CGRectMake(0, 0, DeviceWidth, 0.5f)];
    [separatorView setBackgroundColor:RGBA(225, 225, 225, 1)];
    [self.bottomView addSubview:separatorView];
    
    for (int i = 0; i<2; i++) {
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(likeBtnWidth*(i+1), (40-22)/2, 0.45, 22)];
        line.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.6];
        [self.bottomView addSubview:line];
    }
    // 添加底部按钮视图
    [self.view addSubview:self.bottomView];
   // self.bottomView.hidden = YES;
}

-(UILabel *)labelStyle:(UILabel *)label//统一风格
{
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:FontName size:11];//改字体和大小
    return label;
}

#pragma mark - tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserDataEditCell *cell = nil;
    VoiceCell *voiceCell = nil;
    UserDataEditTagCell *tagCell = nil;
    if (indexPath.section == 0 ||indexPath.section == 2) {
        static  NSString *CellIdentifier = @"UserDataCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (cell == nil) {
            cell = [[UserDataEditCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        
        
        //标题设置
        cell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
        //如果数据是数组则拆分出来拼接成字符串
        cell.contentLabel.text = self.userDetailsArr[indexPath.section][indexPath.row];

        if ([self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"职业"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"内心独白"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"顾问印象"]) {
            cell.contentLabel.frame = CGRectMake(90, 0, DeviceWidth-120, [Utils LabeSizeLabelheight:self.userDetailsArr[indexPath.section][indexPath.row] Font:[UIFont fontWithName:FontName size:14]].height+(50-16.023438));
        }else{
            cell.contentLabel.frame = CGRectMake(90, 0, DeviceWidth-120, 50);
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        
        if ([cell.titleLabel.text isEqualToString:@"声线"]) {
            
            static  NSString *CellIdentifier = @"VoiceCell";
            voiceCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if  (voiceCell == nil) {
                voiceCell = [[VoiceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            voiceCell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
            if (self.voiceArray.count != 0) {
                MLVoice *voice = self.voiceArray[0];
                [voiceCell.voiceBtn setTitle:!(long)voice.time ? @"":[NSString stringWithFormat:@"%ld\"",(long)voice.time] forState:UIControlStateNormal];
                [voiceCell.voiceBtn addTarget:self action:@selector(playVoice:) forControlEvents:UIControlEventTouchUpInside];
                voiceCell.voiceBtn.tag = indexPath.row;
            }
            [voiceCell setSelectionStyle:UITableViewCellSelectionStyleNone];

            return voiceCell;
        }
        
        return cell;
    }else{
        
        NSString *CellIdentifier = [NSString stringWithFormat:@"cell%@",self.userInfoArr[indexPath.section][indexPath.row]];
        tagCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (tagCell == nil) {
            tagCell = [[UserDataEditTagCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        
        tagCell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
//        if ([tagCell.titleLabel.text isEqualToString:@"我想"]) {
//            tagCell.tagListView.canRemoveTags = NO;
//            [tagCell.tagListView.tags setArray:self.userData.want_tags];
//            
//            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                self.h1 = tagCell.tagListView.collectionView.contentSize.height;
//            }
//            
//        }else
            if ([tagCell.titleLabel.text isEqualToString:@"理想对象"]){
            tagCell.tagListView.canRemoveTags = NO;
            
            [tagCell.tagListView.tags setArray:self.userData.ideal_tags];
            
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h2 = tagCell.tagListView.collectionView.contentSize.height;
            }
            
        }else
//            if ([tagCell.titleLabel.text isEqualToString:@"特技"]) {
//            tagCell.tagListView.canRemoveTags = NO;
//            [tagCell.tagListView.tags setArray:self.userData.special];
//            
//            
//            
//            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                self.h3 = tagCell.tagListView.collectionView.contentSize.height;
//            }
//           
//
//        }else
            if ([tagCell.titleLabel.text isEqualToString:@"兴趣"]){
            tagCell.tagListView.canRemoveTags = NO;
          
            [tagCell.tagListView.tags setArray:self.userData.like_tags];
            
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h4 = tagCell.tagListView.collectionView.contentSize.height;
            }
            
        }
        //[tagCell cellframe];
        [tagCell setSelectionStyle:UITableViewCellSelectionStyleNone];

        return tagCell;
        

    }
    

    
        //恋爱技能

//        // 声线的cell
//        if (indexPath.section == 1 && [self.voiceArray count]) {
//            MLVoice *voice = self.voiceArray[indexPath.row];
//            if (indexPath.row == 0) {
//                voiceCell.titleLabel.text = @"声线";
//            }
//            [voiceCell.voiceBtn setTitle:voice.theme forState:UIControlStateNormal];
//            [voiceCell.voiceBtn addTarget:self action:@selector(playVoice:) forControlEvents:UIControlEventTouchUpInside];
//            voiceCell.voiceBtn.tag = indexPath.row;
//            return voiceCell;
//        } else {
//            cell.contentLabel.textColor = [UIColor blackColor];
//            cell.titleLabel.text = [[self.userSkillsTitleArr objectAtIndex:indexPath.section ] objectAtIndex:indexPath.row];
//            
//            if ([[[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isKindOfClass:[NSArray class]]) {
//                NSString *str = [[NSString alloc]init];
//                for (int i = 0 ; i < [[[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]count]; i++) {
//                    if (i == [[[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] count]-1) {
//                        str = [str stringByAppendingString:[NSString stringWithFormat:@"%@",[[[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectAtIndex:i]]];
//                    }else{
//                        str = [str stringByAppendingString:[NSString stringWithFormat:@"%@、",[[[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectAtIndex:i]]];
//                    }
//                }
//                cell.contentLabel.text = str;
//            }else{
//                cell.contentLabel.text = [[self.userSkillsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
//            }
//        }

    
//    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.userInfoArr count];
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.userInfoArr objectAtIndex:section] count];
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if ([self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"职业"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"内心独白"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"顾问印象"]) {
        return [Utils LabeSizeLabelheight:self.userDetailsArr[indexPath.section][indexPath.row] Font:[UIFont fontWithName:FontName size:14]].height+(50-16.023438);
    }
    
    if (section == 1){
        NSString *Title = self.userInfoArr[indexPath.section][indexPath.row];
        CGFloat height = 50;
        
//        if ([Title isEqualToString:@"我想"]) {
//            height = self.h1;
//        }else
            if ([Title isEqualToString:@"理想对象"]){
            height = self.h2;
        }else
//            if ([Title isEqualToString:@"特技"]){
//            height = self.h3;
//        }else
            if ([Title isEqualToString:@"兴趣"]){
            height = self.h4;
        }

        if (height <50) {
            return 50;
        }else{
            return height;
        }

    }else{
        return 50;
    }

}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    //头cell
    UIView *headLabel = [[UIView alloc]init];
    headLabel.backgroundColor = UIColorFromRGB(0xececec);
    return headLabel;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    return 10;
}

- (void)dealloc
{
    if (self.updateAudioUITimer) {
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - user interation

// 点击喜欢当前用户
- (void)likeUserAction {
    [AVAnalytics event:@"喜欢（个人资料）"]; // 通知服务器一个点击事件。
    if (![Utils userinit:self]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [ShareData shareData].isLike = YES;
    if (self.is) {
        
    }else{
        self.is = YES;//开始请求数据
         ShareData *shareData = [ShareData shareData];
       // MLTabBar *tabBar = (MLTabBar *)self.tabBarController;
       // MLHomeViewController *homeView = (MLHomeViewController *)tabBar.homeNavigation.topViewController;
        if (self.likeBtn.selected) {
            __weak MLUserDataViewController *weakSelf = self;
            AVQuery *likeData = [MLUserLike query];
            [likeData whereKey:@"user" equalTo:[MLUser currentUser]];
            [likeData whereKey:@"likeUser" equalTo:self.userData];
            [likeData deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSDictionary *params = @{@"userId": weakSelf.userData.objectId};
                weakSelf.is = NO;//请求完成
                if (!error) {
                    //修改喜欢的状态
                    weakSelf.likeBtn.selected = NO;
                    NSString *str = [[ShareData shareData].likeUserDic objectForKey:weakSelf.userData.objectId];
                    [Utils removeObjectForLoveUserObjectID:weakSelf.userData.objectId];
                    NSInteger count = [str integerValue];
                    count--;
                    str = [NSString stringWithFormat:@" %ld",(long)count];
                    [weakSelf.likeBtn setTitle:str forState:UIControlStateNormal];
                    [shareData.likeUserDic setObject:str forKey:weakSelf.userData.objectId];
                    [[weakSelf.likeBtn layer] setBorderColor:[UIColor grayColor].CGColor];
                    [AVCloud callFunctionInBackground:@"disLikeUser" withParameters:params block:^(id object, NSError *error) {
                    }];
                }
            }];
            
           
        }else {
            MLUserLike *userLike = [MLUserLike object];
            userLike.user = [MLUser currentUser];
            userLike.likeUser = self.userData;
            __weak MLUserDataViewController *weakSelf = self;
            [userLike saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                weakSelf.is = NO;//请求完成
                if (!error) {
                    NSString *str = [[ShareData shareData].likeUserDic objectForKey:weakSelf.userData.objectId];
                    NSInteger count = [str integerValue];
                    count++;
                    str = [NSString stringWithFormat:@" %ld",(long)count];
                    [weakSelf.likeBtn setTitle:str forState:UIControlStateNormal];
                    [[ShareData shareData].likeUserDic setObject:str forKey:weakSelf.userData.objectId];
                     [Utils savePassLoveUserObjectID:weakSelf.userData.objectId];
                   
                    // 标记已喜欢的状态
                    NSDictionary *params = @{@"userId": weakSelf.userData.objectId};
                    [AVCloud callFunctionInBackground:@"likeUser" withParameters:params block:^(id object, NSError *error) {
                        
                        if (error) {
                            //   [HUD Prompt:@"网络错误,请重试"];
                        }else{
                            NSDictionary *params = @{@"touserId": weakSelf.userData.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"msg":@"给你点赞了哦"};
                            [AVCloud callFunctionInBackground:@"sendNewLikerMsg" withParameters:params block:^(id object, NSError *error) {
                                if (error) {
                                    // [HUD Prompt:@"网络错误,请重试"];
                                }else{
                                    
                                }
                            }];
                            NSString *str = [NSString stringWithFormat:@"%@喜欢了你，快去翻翻看",[MLUser currentUser].nickname];
                            NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  str, @"alert",
                                                  @"default", @"sound",NOTIFICATION_TYPE_NEW_LIKE_PUSH,@"action",
                                                  nil];
                           
                            AVPush *push = [[AVPush alloc] init];
                            //正式需要注销下面代码
                          //  [AVPush setProductionMode:NO];
                            [push setChannels:[NSArray arrayWithObjects:self.userData.objectId, nil]];
                            [push setData:data];
                            [push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                                NSLog(@"error%@",error);
                            }];
                        }
                    }];
                    //  修改喜欢的状态
                    weakSelf.likeBtn.selected = YES;
                    [[weakSelf.likeBtn layer] setBorderColor:APPCOLOR(1).CGColor];
                    NSLog(@"成功");
                }else{
                    NSLog(@"%@",error);
                }
                
                
               
            }];
        }
    }
    
    
    
}


// 点击去聊天
- (void)goToChatAction {
    
    if (![Utils userinit:self]) {
        return;
    }
    
//
    [self viewWillDisappear:YES];
    [self viewDidDisappear:YES];
    
    if (_userData.type == 0) {
        [AVAnalytics event:@"实习恋人聊天按钮点击"]; // 通知服务器一个点击事件。
    }else{
        [AVAnalytics event:@"无独团聊天按钮点击"]; // 通知服务器一个点击事件。
    }
    
    if (_popbool != YES) {
        // 建立会话, 跳转到聊天页面
//        MLTabBar *tabBar = (MLTabBar *)self.tabBarController;
//        if (tabBar.selectedIndex != 2) {
//            tabBar.selectedIndex = 2;
//        }
        
        if(self.isLovein){
//            [self.navigationController popToRootViewControllerAnimated:NO];
//            NSDictionary *dic=@{@"user":self.userData};
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"isLoveVC" object:self userInfo:dic];
        }else{
//            ChatListViewController *chatListView = (ChatListViewController *)tabBar.msgNavigation.viewControllers[0];
//            [self.navigationController popToRootViewControllerAnimated:NO];
//            [chatListView startPrivateChat:self.userData];
        }
        
        // 添加到聊天对象字典
      //  [self.chatterUsers setObject:user forKey:user.objectId];
        // 跳转到聊天页面
    //    ChatViewController *chatVC = [[ChatViewController alloc]initWithConversationChatter:self.userData.objectId conversationType:eConversationTypeChat];
        ChatViewController * chatVC = [[ChatViewController alloc] initWithChatter:self.userData.objectId conversationType:eConversationTypeChat];
       
        chatVC.chatUser = self.userData;
        chatVC.title = self.userData.nickname;
        chatVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatVC animated:YES];
        
        MLUser *nUser = [[ShareData shareData].chatterUsers objectForKey:self.userData.objectId];
        if (nUser) {
            
        }else{
            //不存在,则加入
             [[ShareData shareData].chatterUsers setObject:self.userData forKey:self.userData.objectId];
            [Utils saveChatUserDataNicknameUser:self.userData];
        }
        
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
   // }
    
}


#pragma mark voice play

- (void)playVoice:(UIButton *)sender {
    if ([self.player isPlaying]) {
        [self.player stopPlaying];
        
        // 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
        
        [sender setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
    }
    
    if(self.voiceFileArray&&self.voiceFileArray.count){
        self.amrReader.filePath = self.voiceFileArray[0];
        self.voicePlayIndex = 0;
        self.voicePlayStatus = 3;
        [self.player startPlaying];
        self.updateAudioUITimer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(updateVoiceBtnUI) userInfo:nil repeats:YES];
    }
    
}

- (void)updateVoiceBtnUI {
    
    if ( [self.voiceArray count]) {
        // 更新播放按钮显示
        VoiceCell *cell = (VoiceCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        if ([self.player isPlaying]) {
            // 更新图片显示
            if (3 == self.voicePlayStatus) {
                self.voicePlayStatus = 1;
            } else {
                self.voicePlayStatus++;
            }
            if (cell.voiceBtn) {
                NSString *bgImgName = [NSString stringWithFormat:@"voice_play_%ld", (long)self.voicePlayStatus];
                [cell.voiceBtn setImage:[UIImage imageNamed:bgImgName] forState:UIControlStateNormal];
            }else{
                // 播放结束, 停止计时器
                [self.updateAudioUITimer invalidate];
                self.updateAudioUITimer = nil;
            }
            
        } else {
            // 播放结束, 停止计时器
            [self.updateAudioUITimer invalidate];
            self.updateAudioUITimer = nil;
            
            [cell.voiceBtn setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
        }
    }else{
        // 播放结束, 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
    }
}
- (NSString *)avatarWithChatter:(NSString *)chatter{
    //    return @"http://img0.bdstatic.com/img/image/shouye/jianbihua0525.jpg";
    return nil;
}

// 根据环信id得到要显示用户名，如果返回nil，则默认显示环信id
- (NSString *)nickNameWithChatter:(NSString *)chatter{
    return chatter;
}
//用户类型改变,
- (void)chatUserTypeDataChangeUser:(MLUser *)chatUser
{
    
    //[self.chatterUsers setObject:chatUser forKey:chatUser.objectId];
    if ([ShareData shareData].friends) {
        //判断是否已经是好友
        for (int i = 0; i<[ShareData shareData].friends.count; i++) {
            MLUser *f = (MLUser *)[ShareData shareData].friends[i];
            if([f.objectId isEqualToString:chatUser.objectId]){
                [[ShareData shareData].friends replaceObjectAtIndex:i withObject:chatUser];
                [Utils savePassFriendObjectID:chatUser.objectId];
                break;
            }
        }
    }
    if ([self.userData.objectId isEqualToString:chatUser.objectId]) {
        self.userData = chatUser;
    }
    
    NSDictionary *dic=@{@"user":chatUser};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chatUserTypeDataChange" object:self userInfo:dic];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addChatterUsers" object:self userInfo:dic];
}

@end
